<template>
  <div id="login">
    <!-- 加载动画 -->
    <load v-if="!isLoaded" />
    <!-- 显示正常内容 -->
    <div v-if="isLoaded" class="center">
      <div class="login_container">
        <div class="login">
          <div class="title">
            <span>在线学习平台</span>
          </div>
          <div class="login_form">
            <el-form
              ref="form"
              :model="loginformUser"
              label-width="80px"
              @keyup.enter="onSubmit"
            >
              <el-form-item>
                <el-input
                  v-model="loginformUser.username"
                  placeholder="请输用户名"
                  prefix-icon="el-icon-user-solid"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-input
                  type="password"
                  v-model="loginformUser.password"
                  placeholder="请输入密码"
                  prefix-icon="el-icon-lock"
                >
                </el-input>
              </el-form-item>
              <el-form-item>
                <div style="float: left; width: 240px">
                  <el-input
                    type="text"
                    v-model="loginformUser.code"
                    placeholder="请输入验证码"
                    width="120%"
                  >
                  </el-input>
                </div>
                <div style="float: right; margin-top: 2px">
                  <el-image
                    @click="refreshCode"
                    style="width: 100px; height: 36px"
                    :src="this.url"
                  ></el-image>
                </div>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="agreement" style="color: rgb(71 68 68)"
                  >我已阅读并同意</el-checkbox
                >
                <span>《用户协议》</span>
              </el-form-item>
              <el-form-item>
                <el-button
                  :loading="loading"
                  type="primary"
                  style="width: 100%"
                  @click="onSubmit"
                >
                  {{ loading ? "登录中..." : "登录" }}
                </el-button>
              </el-form-item>
            </el-form>
            <div style="text-align: center; margin-top: 10px">
              <span @click="toRegister" class="account">没有账号？去注册</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
  
  <script>
import load from "../loadViews/index.vue";
import { onMounted } from "vue";
export default {
  name: "login",
  components: {
    load,
  },
  data() {
    return {
      loginformUser: {
        username: "",
        password: "",
        code: "",
        uuid: "", // 验证码的uuid
      },
      loading: false, // 用于控制加载图标的显示
      url: "",
      agreement: false, // 是否同意用户协议
      isLoaded: false, // 是否加载完成
      userInfo: [],
    };
  },
  methods: {
    loaded() {
      setTimeout(() => {
        this.isLoaded = true; // 将加载状态设置为已完成
      }, 700);
    },
    //获取验证码
    getCode() {
      this.$http.get("/captchaImage").then((res) => {
        this.url = "data:image/gif;base64," + res.data.img;
        this.loginformUser.uuid = res.data.uuid;
      });
    },

    // 登录按扭 密码登录
    async onSubmit() {
      if (!this.agreement) {
        this.$message.warning("请先同意用户协议");
        return;
      }

      this.loading = true; // 显示加载图标
      try {
        const res = await this.$http.post(
          "/api/sysUser/loginByPwd",
          this.loginformUser
        );
        this.loading = false; // 隐藏加载图标
        if (res.data.code === 200) {
          // 存储 token
          localStorage.setItem("token", res.data.data.token);
          localStorage.setItem("username", this.loginformUser.username);
          localStorage.setItem("password", this.loginformUser.password);

          // 连接 WebSocket
          const socket = new WebSocket(
            `ws://127.0.0.1:8585/singleChat/${this.loginformUser.username}`
          );
          socket.onopen = function () {
            console.log("连接成功");
          };

          this.$message.success(res.data.msg);

          // **确保用户信息获取完再执行跳转逻辑**
          await this.getUserInfo();

          console.log(this.userInfo); // 现在可以正确打印了

          if (!this.userInfo.jobTitle) {
            this.$router.push("/complete");
          } else {
            this.$router.push("/");
          }
        } else {
          this.$message.error(res.data.msg);
        }
      } catch (error) {
        this.loading = false; // 隐藏加载图标
        this.$message.error("登录失败，请稍后再试");
      }
    },

    async getUserInfo() {
      try {
        const res = await this.$http.get("/api/sysUser/detail");
        this.userInfo = res.data.data;
      } catch (error) {
        console.error("获取用户信息失败", error);
      }
    },
    handleEnterKey(event) {
      if (event.key === "Enter" && this.isFormValid()) {
        this.onSubmit();
      }
    },
    isFormValid() {
      // 检查表单是否有数据
      return this.loginformUser.username && this.loginformUser.password;
    },
    toRegister() {
      this.$router.push("/register");
    },

    refreshCode() {
      // 刷新验证码
      this.getCode();
    },

    // 记住密码
    rememberPwd() {
      if (
        localStorage.getItem("username") != null &&
        localStorage.getItem("password") != null
      ) {
        this.loginformUser.username = localStorage.getItem("username");
        this.loginformUser.password = localStorage.getItem("password");
      }
    },
  },
  mounted() {
    this.loaded();
    this.getCode();
    // 在组件挂载后监听回车键事件
    window.addEventListener("keyup", this.handleEnterKey);
    this.rememberPwd();
  },
  beforeDestroy() {
    // 在组件销毁前移除回车键事件监听
    window.removeEventListener("keyup", this.handleEnterKey);
  },
};
</script>
  
  
  
  
  
<style lang="less" scoped>
#login {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow: hidden;
  .center {
    position: relative;
    height: 650px;
    width: 100%;
    // background: url("../../assets/images/bck.jpg") no-repeat;
    background-size: cover;

    .login_container {
      position: absolute;
      width: 450px;
      height: 100%;
      left: 40%;
      top: 165px;
      .login {
        padding: 20px 20px 20px 20px;
        width: 350px;
        border-radius: 10px;
        box-shadow: 2;
        padding: 20px;

        background: rgb(
          255 255 255 / 4%
        ); /* 使用 rgba() 函数设置背景颜色和透明度 */
        border-radius: 10px;
        box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.2); /* 这里也可以使用 rgba() 函数设置阴影的颜色和透明度 */
        .title {
          width: 100%;
          height: 50px;
          span {
            margin-left: 110px;
            height: 50px;
            line-height: 50px;
            text-align: center;
            font-size: 18px;
            cursor: pointer;
          }
          span.active {
            color: #3776da;
          }
        }
      }
      .login_form {
        box-shadow: 2;
      }
    }
  }
  /deep/ .el-form-item__content {
    margin-left: 0 !important;
  }
  .account {
    color: #3776da;
    cursor: pointer;
  }
  .account:hover {
    color: #409eff;
  }
}
</style>